import React, {useState, useEffect} from "react";
import "./examine.scss";
import {
    Button,
    Drawer,
    PageHeader,
    Tabs,
    Form,
    Radio,
    Input,
    Row,
    Col,
    Space,
    message,
    Collapse,
    Divider,
    Select, Table
} from "antd";
import {
    ExclamationCircleOutlined,
    LeftOutlined,
    MinusCircleOutlined,
    PlusOutlined,
    RightOutlined
} from "@ant-design/icons";
import {getRecordTask} from "../../../api/recordTaskApi"
import Detail from "../../detail/detail-component/Detail";
import RecordProcessHistory from "../../detail/record_process_history/RecordProcessHistory";
import {getProcessHistory} from "../../../api/recordProcessHistoryApi";
import {formatProcessHistory} from "../../record_manage/recordManageUtils";
import {getAuditRecordAndAssignTaskByRecordTaskId} from "../../../api/auditRecordApi";
import UploadFile from "../../upload_file/UploadFile";
import {auditRecord} from "../../../api/auditRecordApi";
import Modal from "antd/es/modal/Modal";
import {getParkLotSiteSurveyInfo} from "../../../api/siteSurveyApi";

function Examine(props) {
    const {TabPane} = Tabs;
    const {Panel} = Collapse;
    const {Option} = Select;

    const recordTaskId = props.match.params?.recordTaskId;

    const [recordTask, setRecordTask] = useState({});
    const [recordProcessHistoryArr, setRecordProcessHistoryArr] = useState([]);
    const [auditRecordArr, setAuditRecordArr] = useState([]);
    const [visible, setVisible] = useState(true);
    const [drawerButtonStyle, setDrawerButtonStyle] = useState({
        height: "35px",
        transform: "translateX(-507px) translateY(330px)"
    });
    // const [fileList, setFileList] = useState([]);
    const [examine, setExamine] = useState({result: "1", reason: ""});
    const [isPass, setIsPass] = useState(true);
    const [assignTaskItems, setAssignTaskItems] = useState([]);
    const [isSubmittingAuditRecord, setIsSubmittingAuditRecord] = useState(false);
    const [parkLotSiteSurveyInfoArr, setParkLotSiteSurveyInfoArr] = useState(null);
    const [siteSurveyInfo, setSiteSurveyInfo] = useState([]);
    const [siteSurveyOptionValue, setSiteSurveyOptionValue] = useState("0");
    // const [examineResult, setExamineResult] = useState(1);

    let addAssignItem = null;

    const formItemLayout = {
        labelCol: {
            span: 4,
        },
        wrapperCol: {
            span: 19,
        },
        labelAlign: "left"
    }

    const columns = [
        {
            title: '添加+可快捷添加到上报问题中',
            dataIndex: 'add',
            key: 'add',
            render: (text, record) => <a onClick={() => {
                handleAddAssignTaskItem(record);
            }}>{<PlusOutlined/>}</a>,
            align: "center",
            width: 230
        },
        {
            title: '序号',
            dataIndex: 'order',
            key: 'order',
            align: 'center',
            width: 50
        },
        {
            title: '检查内容',
            dataIndex: 'content',
            key: 'content',
        },
    ];

    useEffect(() => {
        getRecordTaskData(recordTaskId);
    }, [])

    const getRecordTaskData = (recordTaskId) => {
        getRecordTask(recordTaskId).then(r => {
            setRecordTask(r);
        }, e => {
            return e;
        });
    }

    const getProcessHistoryArr = (recordTaskId) => {
        getProcessHistory(recordTaskId).then(r => {
            formatProcessHistory(r);
            console.log(r);
            setRecordProcessHistoryArr(r);
        }, e => {
            return e;
        });
    }

    const getAuditRecordArr = (recordTaskId) => {
        getAuditRecordAndAssignTaskByRecordTaskId(recordTaskId).then(r => {
            console.log(r);
            setAuditRecordArr(r);
        }, e => {
            return e;
        });
    }

    const getParkLotSiteSurveyInfoArr = () => {
        getParkLotSiteSurveyInfo().then(r => {
            for (let i = 0; i < r.length; i++) {
                r[i].json = JSON.parse(r[i].json);
            }
            setSiteSurveyInfo(getSiteSurveyData(r, 0));
            setParkLotSiteSurveyInfoArr(r);
        });
    }

    const getPageHeader = () => {
        const stage = recordTask.stage;
        if (stage === 1) {
            return "区停车办资料初核";
        } else if (stage === 2) {
            return "区停车办现场勘察";
        } else if (stage === 3) {
            return "区停车办资料复审";
        }
    }

    const getSiteSurveyData = (parkLotSiteSurveyInfoArr, index) => {
        const siteSurveyInfo = parkLotSiteSurveyInfoArr[index].json;
        const tempSiteSurveyInfo = [];
        for (let i = 0; i < siteSurveyInfo.length; i++) {
            tempSiteSurveyInfo[i] = {
                key: i + 1,
                order: i + 1,
                content: siteSurveyInfo[i].name,
            };
        }
        return tempSiteSurveyInfo;
    }

    const handleTabsChange = (activeKey) => {
        if (activeKey === "2") {
            getProcessHistoryArr(recordTaskId);
            getAuditRecordArr(recordTaskId);
        }
        if (activeKey === "3" && !parkLotSiteSurveyInfoArr) {
            handleIsVisible();
            getParkLotSiteSurveyInfoArr();
        }
        // console.log(parkLotSiteSurveyInfoArr);
    }

    const handleIsVisible = () => {
        if (visible) {
            setVisible(false);
            setDrawerButtonStyle({height: "35px", transform: "translateX(0) translateY(330px)"});
        } else {
            setVisible(true);
            setDrawerButtonStyle({height: "35px", transform: "translateX(-507px) translateY(330px)"});
        }
    }

    const handleAuditRecordValuesChange = (changedValues, allValues) => {
        const examineValue = allValues.examine;
        // console.log("---------");
        // console.log(examine);
        // console.log(examineValue);
        setIsPass(examineValue.result === "1");
        setExamine(examineValue);
    }

    const handleAssignTaskValuesChange = (changeValues, allValues) => {
        setAssignTaskItems(allValues.assignTaskItems);
        // console.log("-------------");
        // console.log(allValues);
        // console.log(assignTaskItems);
    }

    const handleSiteSurveyOptionValueChange = (value) => {
        setSiteSurveyInfo(getSiteSurveyData(parkLotSiteSurveyInfoArr, value));
        setSiteSurveyOptionValue(value);
    }

    const handleAddAssignTaskItem = (record) => {
        if (!visible) {
            handleIsVisible();
        }
        if (examine.result === "1") {
            message.error("审核不通过时才能添加整改问题");
            return;
        }
        for (let i = 0; i < assignTaskItems.length; i++) {
            if (assignTaskItems[i].name===record.content){
                message.error("已添加该整改项");
                return;
            }
        }
        addAssignItem({name: record.content});
        message.success("添加成功");
    }

    const submitConfirm = () => {
        if (examine.result === "0") {
            for (let i = 0; i < assignTaskItems.length; i++) {
                if (!assignTaskItems[i]?.name) {
                    message.error("整改任务名称不能为空");
                    return;
                }
            }
        }
        if (!examine.reason) {
            message.error("审核意见不能为空");
            return;
        }

        Modal.confirm({
            title: '确认信息',
            icon: <ExclamationCircleOutlined/>,
            content: '确定提交审核信息吗？',
            okText: '确认',
            cancelText: '取消',
            onOk: submitAuditRecord
        });
    }

    const submitAuditRecord = () => {
        const userInfo = JSON.parse(localStorage.getItem("data"));
        const auditResult = {};
        let auditRecordInfo = {
            parkLotRecordTaskId: recordTaskId,
            type: 0,
            stage: recordTask.stage,
            status: Number(examine.result),
            auditReason: examine.reason,
            auditorId: userInfo.userId,
            auditorName: userInfo.realName
        };

        if (examine.result === "0") {
            const tempAssignTaskItems = [...assignTaskItems];
            for (let i = 0; i < tempAssignTaskItems.length; i++) {
                tempAssignTaskItems[i]["status"] = 0;
            }
            auditRecordInfo["recordAssignTasks"] = [{
                assignTaskItems: tempAssignTaskItems
            }];
        }

        // console.log(recordTask);
        // console.log(auditRecordInfo);
        auditResult["recordTask"] = recordTask;
        auditResult["auditRecord"] = auditRecordInfo;

        // console.log(auditResult);

        setIsSubmittingAuditRecord(true);
        auditRecord(auditResult).then(r => {
            console.log(r);
            let path = "";
            const stage = recordTask.stage;
            if (stage === 1) {
                path = "/todo/firstTrial?menu=todo"
            } else if (stage === 2) {
                path = "/todo/siteInvestigation?menu=todo";
            } else if (stage === 3) {
                path = "/todo/recheck?menu=todo";
            }
            props.history.push(path);
        })
    }

    const getDrawerButtonDirection = () => {
        if (visible) {
            return <RightOutlined/>;
        } else {
            return <LeftOutlined/>;
        }
    }

    const getTabNode = (name, spaceNumber = 0) => {
        const spaceArr = [];
        for (let i = 0; i < spaceNumber; i++) {
            spaceArr.push(<span key={i}>&nbsp;</span>);
        }

        return (
            <span>
                {spaceArr}{name}{spaceArr}
            </span>
        );
    }

    return (
        <div className={"examine"}>
            <PageHeader title={<span className={"page-header-title"}>{getPageHeader()}</span>}
                        onBack={() => window.history.back()}
            />

            <div className={"examine-record-task"}>
                <Tabs defaultActiveKey="1" onChange={(activeKey) => {
                    handleTabsChange(activeKey)
                }}>
                    <TabPane tab="基本信息" key="1">
                        <Detail recordTask={recordTask}/>
                    </TabPane>

                    <TabPane tab="流程履历" key="2">
                        <RecordProcessHistory recordTaskSno={recordTask?.sno}
                                              recordProcessHistoryArr={recordProcessHistoryArr}
                                              auditRecordArr={auditRecordArr}
                        />
                    </TabPane>

                    <TabPane tab={<span>{recordTask.stage === 2 ? "现场勘察" : ""}</span>} key="3">
                        <Collapse defaultActiveKey={['1']} ghost>
                            <Panel header={
                                <>
                                    <span>现场勘察</span>
                                    <Button type={"link"}>打印备案申请表</Button>
                                </>
                            } key="1">
                                <Divider className={"collapse-panel-divider"}/>

                                <div className={"site-survey-row"}>
                                    <Row>
                                        <Col span={12}>
                                            <span>停车场名称：{recordTask.name}</span>
                                        </Col>
                                        <Col span={12}>
                                            <span>停车场等级：{recordTask?.parkLevel}</span>
                                        </Col>
                                    </Row>
                                </div>


                                <div className={"site-survey-row"}>
                                    <Select defaultValue={siteSurveyOptionValue}
                                            onChange={handleSiteSurveyOptionValueChange} size={"small"}
                                            style={{width: "25%"}}>
                                        <Option value="0">室外停车场现场核查情况表</Option>
                                        <Option value="1">普通级室内停车场现场核查情况表</Option>
                                        <Option value="2">特级室内停车场现场核查情况表</Option>
                                    </Select>
                                </div>


                                <div className={"site-survey-row"}>
                                    <Table columns={columns} dataSource={siteSurveyInfo} pagination={false}
                                           size={"middle"}/>
                                </div>
                            </Panel>
                        </Collapse>
                    </TabPane>
                </Tabs>
            </div>

            <Drawer
                placement="right"
                closable={false}
                visible={true}
                width={15}
                mask={false}
                bodyStyle={{padding: 0}}
                contentWrapperStyle={{boxShadow: "none"}}
                style={drawerButtonStyle}
            >
                <Button className={"drawer-button"} type={"primary"} size={"small"} onClick={handleIsVisible}>
                    {getDrawerButtonDirection()}
                </Button>

                <Drawer placement={"right"} closable={false} visible={visible} mask={false} width={510}
                        footer={
                            <div className={"examine-drawer-footer"}>
                                <Button type={"primary"}
                                        onClick={submitConfirm}
                                        loading={isSubmittingAuditRecord}
                                >
                                    {isPass ? "审核通过" : "生成整改任务并提交"}
                                </Button>
                            </div>
                        }
                >
                    <Tabs defaultActiveKey="1" size={"large"} centered={false} tabBarGutter={0}>
                        <TabPane
                            tab={getTabNode("审核", 19)}
                            key="1"
                        >
                            <Form
                                name={"examine_form"}
                                {...formItemLayout}
                                initialValues={{
                                    examine
                                }}
                                onValuesChange={handleAuditRecordValuesChange}
                            >
                                <Form.Item name={["examine", "result"]} label="审核结果" required={true}>
                                    <Radio.Group value={"0"}>
                                        <Radio value="1">审核通过</Radio>
                                        <Radio value="0">审核不通过</Radio>
                                    </Radio.Group>
                                </Form.Item>

                                <Form.Item name={["examine", "reason"]} label="审核意见" required={true}
                                           extra={<a>保存为默认意见</a>}>
                                    <Input.TextArea rows={6} placeholder={"请输入"}/>
                                </Form.Item>
                            </Form>

                            <div style={{display: isPass ? "none" : "block"}}>
                                <Row>
                                    <Col span={24}>
                                        <span>整改意见：</span>
                                    </Col>
                                </Row>

                                <Form name="dynamic_form_nest_item" autoComplete="off"
                                      onValuesChange={handleAssignTaskValuesChange}>
                                    <Form.List name="assignTaskItems">
                                        {(fields, {add, remove}) => {
                                            addAssignItem = add;
                                            return (
                                                <>
                                                    {fields.map(({key, name, fieldKey, ...restField}) => (
                                                        <Space key={key} style={{display: 'flex', marginBottom: 8}}
                                                               align="baseline">
                                                            <span>{key + 1}、</span>
                                                            <Form.Item
                                                                {...restField}
                                                                name={[name, 'name']}
                                                                fieldKey={[fieldKey, 'name']}
                                                                // rules={[{required: true, message: 'Missing first name'}]}
                                                            >
                                                                <Input placeholder="整改问题"/>
                                                            </Form.Item>

                                                            <Form.Item
                                                                {...restField}
                                                                name={[name, 'last']}
                                                                fieldKey={[fieldKey, 'last']}
                                                                // rules={[{required: true, message: 'Missing last name'}]}
                                                            >
                                                                <UploadFile/>
                                                            </Form.Item>

                                                            <MinusCircleOutlined onClick={() => remove(name)}/>
                                                        </Space>
                                                    ))}
                                                    <Form.Item>
                                                        <Button type="dashed" onClick={() => add()} block
                                                                icon={<PlusOutlined/>}>
                                                            添加整改项
                                                        </Button>
                                                    </Form.Item>
                                                </>
                                            );
                                        }}
                                    </Form.List>
                                </Form>
                            </div>

                            <Row align={"middle"}>
                                <Col span={5}>
                                    <span>审核结果附件:</span>
                                </Col>
                                <Col span={19}>
                                    <UploadFile/>
                                </Col>
                            </Row>
                        </TabPane>

                        <TabPane
                            tab={getTabNode("上次审核结果", 12)}
                            key="2">
                            Content of Tab Pane 2
                        </TabPane>
                    </Tabs>
                </Drawer>
            </Drawer>
        </div>
    );
}

export default Examine;